//
//  FreeValuationUploadView.swift
//  Kool Car
//
//  Created by huangweiqiang on 2022/4/21.
//

import UIKit
import Photos
import AliyunOSSiOS
import HXPhotoPicker
import JXPhotoBrowser

protocol FreeValuationUploadViewDelegate {
    func selectImage(array: [UpLoadImgModel], hh: CGFloat)
}

class FreeValuationUploadView: UIView {
    var delegate: FreeValuationUploadViewDelegate!
    var titleLab: UILabel!
    var collectionView: UICollectionView!
    var config: PickerConfiguration = .init()
    
    var imgArr: [UpLoadImgModel] = []
    var selectAssets: [PhotoAsset] = []   //相册k选择的图片
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        titleLab = UILabel.init(frame: CGRect.zero)
        titleLab.backgroundColor = UIColor.clear
        titleLab.textAlignment = .left
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleLab.textColor = Theme.titleLabColor
        titleLab.text = MMLocalizedString("ppload_vehicle_pictures", comment: "上传车辆图片（如有）")
        self.addSubview(titleLab)
        
        
        
        let layout = MHCollectionViewFlowlayout()
        let ww = (kScreenWidth - 56 - 10*2)/3
        layout.itemSize = CGSize.init(width: ww, height: 80)
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.register(FreeValuationUploadImgItemCell.self, forCellWithReuseIdentifier: "FreeValuationUploadImgItemCell")
        collectionView.backgroundColor = .clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isScrollEnabled = false
        self.addSubview(collectionView)
        self.addSnpLayout()
    }
    
    func addSnpLayout(){
        
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(0)
            make.right.equalTo(-14)
            make.height.equalTo(20)
        }
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLab.snp.bottom).offset(14)
            make.left.equalTo(0)
            make.right.equalTo(-0)
            make.height.greaterThanOrEqualTo(120)
            make.bottom.equalTo(0)
        }
    }
    
    ///赋值
    func setFreeValuationUploadImgCellData(){
        self.collectionView.reloadData()
        self.updateConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension FreeValuationUploadView: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.imgArr.count > 9 {
            return 9
        }
        return self.imgArr.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FreeValuationUploadImgItemCell", for: indexPath) as! FreeValuationUploadImgItemCell
        cell.atIndex = indexPath.row
        if self.imgArr.count > indexPath.row {
            cell.deleteBtn.isHidden = false
            let model = self.imgArr[indexPath.row]
            cell.imageViewBtn.setImage(nil, for: .normal)
            cell.setUpLoadImgModel(itemModel: model)
            
        }else{
            cell.deleteBtn.isHidden = true
            cell.imageViewBtn.setBackgroundImage(nil, for: .normal)
            cell.imageViewBtn.setImage(UIImage(named: "icon_update"), for: .normal)
        }
        
        cell.delegate = self
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.imgArr.count > indexPath.row {
            self.showImageBig(index: indexPath.row)
        }else{
            self.openBottomSheetView()
        }
        
    }
    
    
    
    func showImageBig(index: Int){
        if self.imgArr.count > index{
            // 实例化
            let browser = JXPhotoBrowser()
            // 浏览过程中实时获取数据总量
            browser.numberOfItems = {self.imgArr.count}
            // 刷新Cell数据。本闭包将在Cell完成位置布局后调用。
            browser.reloadCellAtIndex = { context in
                let model = self.imgArr[context.index]
                let browserCell = context.cell as? JXPhotoBrowserImageCell
                browserCell?.index = context.index
                let collectionPath = IndexPath(item: context.index, section: 0)
                let collectionCell = self.collectionView.cellForItem(at: collectionPath) as? FreeValuationUploadImgItemCell
                let placeholder = model.image
                // 用 SDWebImage 加载
                browserCell?.imageView.sd_setImage(with: URL.init(string: ""), placeholderImage: placeholder)
            }
            // UIPageIndicator样式的页码指示器
            browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
//            browser.pageIndex = arrayIndex
            browser.pageIndex = index
            browser.show()// 展示
        }
    }
    
    
    
    ///选择相机/相册弹框
    private func openBottomSheetView()  {
        let bottomVC = UIAlertController.init(title: MMLocalizedString("please_select", comment: "请选择"), message: nil,  preferredStyle: .actionSheet)
        let acion1 = UIAlertAction.init(title: MMLocalizedString("camera", comment: "相机"), style: .default) { (action) in
            let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) //读取设备授权状态
            if authStatus == .authorized {
                DispatchQueue.main.async {
                    var tempConfig = CameraConfiguration()
                    tempConfig.editor.toolsView.toolOptions = []
                    tempConfig.languageType = XTManageCenter.getHXPhotoPickerLanguage()
                    tempConfig.modalPresentationStyle = .fullScreen
                    tempConfig.allowLocation = false
                    let controller = CameraController.init(config: tempConfig, type: .all, delegate: self)
                    self.viewController()?.present(controller, animated: true)
                }
            }else{
                AVCaptureDevice.requestAccess(for: AVMediaType.video) { (flag) in
                    if flag == false {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            self.alertCamara()
                        }
                    }else{
                        var tempConfig = CameraConfiguration()
                        tempConfig.editor.toolsView.toolOptions = []
                        tempConfig.languageType = XTManageCenter.getHXPhotoPickerLanguage()
                        tempConfig.modalPresentationStyle = .fullScreen
                        tempConfig.allowLocation = false
                        tempConfig.cameraType = .normal
                        let backCamara = AVCaptureDevice.DiscoverySession.init(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back)
                        if backCamara.devices.isEmpty {
                            let frontCamara = AVCaptureDevice.DiscoverySession.init(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .front)
                            if frontCamara.devices.isEmpty {
                                self.makeToast(message: MMLocalizedString("app_cannot_camara", comment: "App无法使用相机功能"))
                                return
                            }else{
                                tempConfig.position = .front
                            }
                        }else{
                            tempConfig.position = .back
                        }
                        let controller = CameraController.init(config: tempConfig, type: CameraController.CaptureType.photo, delegate: self)
                        self.viewController()?.present(controller, animated: true)
                    }
                }
            }
        }
        let acion2 = UIAlertAction.init(title: MMLocalizedString("album", comment: "相册"), style: .default) { (action) in
            //判断相册权限 放在这里， 因为插件第一次判断时，展示空白
            PHPhotoLibrary.requestAuthorization({ (firstStatus) in
                let result = (firstStatus == .authorized)
                if result {
                    //允许APP访问相册
                    DispatchQueue.main.async {
                        var config = PickerConfiguration.default
                        config.languageType = XTManageCenter.getHXPhotoPickerLanguage()
                        config.modalPresentationStyle = .fullScreen
                        config.allowSelectedTogether = false
                        config.maximumSelectedCount = 9
                        config.selectOptions = [.photo]
                        config.photoList.allowAddCamera = false
                        
                        let pickerController = PhotoPickerController.init(picker: config)
                        pickerController.pickerDelegate = self
                        pickerController.autoDismiss = true
                        pickerController.selectedAssetArray = self.selectAssets
                        self.viewController()?.present(pickerController, animated: true)
                    }
                } else {
                    DispatchQueue.main.async {
                        self.alert()
                    }
                }
            })
        }
        let acion3 = UIAlertAction.init(title: MMLocalizedString("cancel", comment: "取消"), style: .cancel) { (action) in
            
        }
        bottomVC.addAction(acion1)
        bottomVC.addAction(acion2)
        bottomVC.addAction(acion3)
        self.viewController()?.present(bottomVC, animated: true, completion: nil)
    }
    
    
    func alert() {
        let alert = UIAlertController(title:MMLocalizedString("app_cannot_album", comment: "App无法使用相册功能"), message: MMLocalizedString("setting_album_path", comment: "请在设置-隐私-相机中允许访问相册"), preferredStyle: .alert)
        let cancelAntion = UIAlertAction(title: MMLocalizedString("cancel", comment: "取消"), style: .default, handler: nil)
        let setAnion = UIAlertAction(title: MMLocalizedString("setting", comment: "设置"), style: .default) { (action) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
            }
        }
        alert.addAction(cancelAntion)
        alert.addAction(setAnion)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
    func alertCamara() {
        let alert = UIAlertController(title: MMLocalizedString("app_cannot_camara", comment: "App无法使用相机功能"), message: MMLocalizedString("setting_camara_path", comment: "请在设置-隐私-相机中允许访问相机"), preferredStyle: .alert)
        let cancelAntion = UIAlertAction(title: MMLocalizedString("cancel", comment: "取消"), style: .default, handler: nil)
        let setAnion = UIAlertAction(title: MMLocalizedString("setting", comment: "设置"), style: .default) { (action) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
            }
        }
        alert.addAction(cancelAntion)
        alert.addAction(setAnion)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
    
    
}


extension FreeValuationUploadView: FreeValuationUploadImgItemCellDelegate {
    
    
    ///删除
    func deleteImageAction(atIndex: NSInteger) {
        if self.imgArr.count == 0 {
            return
        }
        let itemModel = self.imgArr[atIndex]
        if itemModel.uploadStatus == 0 {
            return
        }
        
        if self.imgArr.count > atIndex{
            self.imgArr.remove(at: atIndex)
        }
       
        if self.selectAssets.count > atIndex{
            self.selectAssets.remove(at: atIndex)
        }
       
        self.collectionView.reloadData()
        self.collectionView.layoutSubviews()
        let hh = self.collectionView.collectionViewLayout.collectionViewContentSize.height
        self.delegate.selectImage(array: self.imgArr, hh: hh + 50)
    }
    
}



//相机
extension FreeValuationUploadView: CameraControllerDelegate{
    //完成
    func cameraController(_ cameraController: CameraController, didFinishWithResult result: CameraController.Result, location: CLLocation?) {
        cameraController.dismiss(animated: true) {
            switch result {
                case .image(let image):
                let imgModel = UpLoadImgModel.init()
                imgModel.image = image
                self.imgArr.append(imgModel)
                self.viewController().view.showLoadingHUDText()
                self.startUploadImage()
                default:
                    ()
            }
        }
    }
    
   
}

//相册
extension FreeValuationUploadView: PhotoPickerControllerDelegate{
    func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        pickerController.dismiss(true) {
            let assetArray = result.photoAssets
            self.selectAssets = assetArray
            for image in assetArray{
                let imgModel = UpLoadImgModel.init()
                imgModel.image = image.originalImage
                self.imgArr.append(imgModel)
            }
            self.viewController().view.showLoadingHUDText()
            self.startUploadImage()
            for asset in assetArray {
                //本地图片，查是否有url,没有则上传
                if !asset.isNetworkAsset && asset.localImageAsset?.imageURL == nil {
                    if let image = asset.originalImage {
                        OSSUplooadImageUtil().ossUploadImage(image: image) {[weak self] (pImage ,ossResult) in
                            if let urlStr = ossResult.url, urlStr != "" {
                                if let url = URL.init(string: urlStr) {
                                    var lcoalAsset = LocalImageAsset.init(image: pImage!)
                                    lcoalAsset.imageURL = url
                                    let photoAsset = PhotoAsset.init(localImageAsset: lcoalAsset)
                                    self?.selectAssets.append(photoAsset)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    func pickerController(didCancel pickerController: PhotoPickerController) {
        pickerController.dismiss(animated: true, completion: nil)
    }
    
    ///准备传图片
    func startUploadImage(){

        for (tagIndex, _) in self.imgArr.enumerated() {
            self.uploadBusinessImgStep(atIndex: tagIndex) { imgUrl in
                if imgUrl != "" {
                    self.imgArr[tagIndex].uploadStatus = 1
                    self.imgArr[tagIndex].url = imgUrl!
                }else{
                    self.imgArr[tagIndex].uploadStatus = 2
                }
                self.viewController().view.handleLoading()
                self.collectionView.reloadData()
                self.collectionView.layoutSubviews()
                let hh = self.collectionView.collectionViewLayout.collectionViewContentSize.height
                self.delegate.selectImage(array: self.imgArr, hh: hh + 50)
                
            } failedBlock: {
                self.viewController().view.handleLoading()
                self.imgArr[tagIndex].uploadStatus = 2
                self.collectionView.reloadData()
            }
        }
    }
    
    ///=========================
    ///上传照片-
    @objc func uploadBusinessImgStep(atIndex: NSInteger, successBlock: @escaping (String?)->Void, failedBlock:@escaping ()->Void){
        let model = self.imgArr[atIndex]
        guard let tempData = XTCheckCenter.imageData(model.image) else {
            return
        }
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getOSSToken, objectType: GetOssTokenModel.self, finished: { (response) in
            let resultObj = response as! GetOssTokenModel
            if resultObj.code == "1"{
                self.uploadImageToAliyunOSS(ossModel: resultObj.data!, imgData: tempData, tagIndex: atIndex) { str in
                    successBlock(str)
                } failedBlock: {
                    failedBlock()
                }
            }
        }) { (error) in
            failedBlock()
            printLog(error)
        }
    }
    
    func uploadImageToAliyunOSS(ossModel: GetTokenDataModel, imgData: Data? = nil, tagIndex: NSInteger, completed: @escaping (String?)->Void, failedBlock:@escaping ()->Void) {
        guard imgData != nil else {
            return
        }
      
        let endPoint = String(format: "http://%@.aliyuncs.com/", ossModel.region ?? "")
        let config = OSSClientConfiguration.init()
        let credential = OSSStsTokenCredentialProvider.init(accessKeyId: ossModel.accessKeyId ?? "", secretKeyId: ossModel.accessKeySecret ?? "", securityToken: ossModel.securityToken ?? "")
        let client = OSSClient.init(endpoint: endPoint, credentialProvider: credential, clientConfiguration: config)
        let put = OSSPutObjectRequest.init()
        put.bucketName = ossModel.bucketName ?? ""
        put.objectKey = String(format: "%@%@%_%d.%@",
                               ossModel.fileDir ?? "",
                               XTManageCenter.getDateTimeStringNow(format: "yyyyMMddHHmmss"),
                               tagIndex,
                               imgData?.getImageFormat() ?? "png")
        put.uploadingData = imgData!
       
        let putTask = client.putObject(put)
        
        putTask.waitUntilFinished()
        if (putTask.error == nil) {
            printLog("上传成功")
            let resultUrl = client.presignPublicURL(withBucketName: ossModel.bucketName ?? "", withObjectKey: put.objectKey)
            completed(resultUrl.result as? String)
        }else{
            printLog("上传失败")
            failedBlock()
        }
        putTask.continue(successBlock: {res in
            printLog(res)
            
        })
    }
    
    
}
